package com.deer.wms.ware.task.web;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deer.wms.base.system.model.Area.AreaInfo;
import com.deer.wms.base.system.model.CustInfoBO;
import com.deer.wms.base.system.model.Item.ItemInfo;
import com.deer.wms.base.system.service.AreaInfoService;
import com.deer.wms.base.system.service.ItemInfoService;
import com.deer.wms.inventory.model.Inventory.Inventory;
import com.deer.wms.inventory.model.Inventory.InventoryVo;
import com.deer.wms.inventory.service.InventoryService;
import com.deer.wms.project.root.util.DateUtils;
import com.deer.wms.project.root.util.HttpClient;
import com.deer.wms.system.manage.model.DataDictDetail;
import com.deer.wms.system.manage.service.DataDictDetailService;
import com.deer.wms.ware.task.model.WCS.WcsInfo;
import com.deer.wms.ware.task.service.PushErpService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;

import java.util.*;
import java.util.stream.Collectors;

import static com.deer.wms.project.root.util.CollectionUtils.convertMap;

/**
* Created by  on 2020/06/14.
*/
@RestController
@RequestMapping("/wcs/infos")
public class WcsInfoController {

    @Autowired
    private PushErpService pushErpService;

    private static  WcsInfo wcsInfo ;
    @Autowired
    private DataDictDetailService dataDictDetailService;


    @GetMapping("/getWcsInfo1")
    @ResponseBody
    public static WcsInfo getWcsInfo1(){
        if(wcsInfo==null){
            return  null;
        }else {
            /*Date now = DateUtils.getNowDate();
            long diff = now.getTime() - wcsInfo.getCreateTime().getTime();
            if(diff>5000){  //19895
                return null;
            }*/
            return  wcsInfo;
        }

    }
    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody WcsInfo wcsInfo1) {
        wcsInfo = wcsInfo1;
        wcsInfo.setCreateTime(DateUtils.getNowDateTimeString());
        // wcsInfoService.save(wcsInfo);
        return ResultGenerator.genSuccessResult();
    }


    @GetMapping("/getWcsInfo")
    @ResponseBody
    public Result getWcsInfo() {
        return ResultGenerator.genSuccessResult(wcsInfo);
    }

    @GetMapping("convert/{number}")
    public void convert(@PathVariable Integer number) {
        List<DataDictDetail> dataDictDetails = new ArrayList<>();
        String token = pushErpService.getToken();
        if (ObjectUtil.isNotEmpty(token)) {
            String url;
            url = "https://syecrg.sieyuan.com:44398/api/Item/GetAllItems/" + number;
            //调用erp接口获取数据
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.add("Accept", "application/json");
            httpHeaders.add("Authorization", "Bearer " + token);
            String result = null;

            try {
                result = HttpClient.getRequest(url, null, httpHeaders);
                JSONArray jsonArray = JSONArray.parseArray(result);
                List<CustInfoBO> di = JSONObject.parseArray(jsonArray.toJSONString(), CustInfoBO.class);
                System.out.println(di);
                for (CustInfoBO custInfoBO : di) {
                    DataDictDetail dataDictDetail = new DataDictDetail();
                    dataDictDetail.setDictKey(custInfoBO.getId().toString());
                    dataDictDetail.setDictValue(custInfoBO.getName());
                    dataDictDetails.add(dataDictDetail);
                }
                dataDictDetailService.saveBatch(dataDictDetails);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }



    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private ItemInfoService itemInfoService;

    @Value("${wave.vmi}")
    //VMI仓库id
    private Integer vmiId;

    @Autowired
    private AreaInfoService areaInfoService;
    @GetMapping("/getErpInv")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token",value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    public Result getErpInv(Integer areaId,String itemCode,Integer type) {

        List<AreaInfo> list = areaInfoService.list();
        List<Integer> collect1 = list.stream().filter(item -> ObjectUtil.isNotEmpty(item.getWaveType()) && item.getWaveType() == 2).map(menu -> menu.getErpAreaId()).collect(Collectors.toList());
        Map<Integer, AreaInfo> areaMap = convertMap(list, AreaInfo::getErpAreaId);
        Map<String, Object> map = new HashMap<>();
        List<InventoryVo> inventory = pushErpService.inventory(map);
        List<Inventory> inventories = inventoryService.list(new QueryWrapper<Inventory>()
                .and(w -> w
                        //直发虚仓
                        .or().notIn("asn_stock_id", vmiId)
                        .or().isNull("asn_stock_id")
                )
        );
        Map<String, List<Inventory>> invMap = inventories.stream().collect(Collectors.groupingBy(Inventory::getItemCodeAndStock));
        for (InventoryVo inventoryVo : inventory) {
            AreaInfo areaInfo = areaMap.get(inventoryVo.getStockId());
            inventoryVo.setAsnStockName(areaInfo.getAreaName());
            List<Inventory> inventoryList = invMap.get(inventoryVo.getItemCodeAndStock()    );
            if (ObjectUtil.isNotEmpty(inventoryList)) {

                inventoryVo.setItemName(inventoryList.get(0).getItemName());
                double sum = 0.00;

                if (ObjectUtil.isNotEmpty(inventoryVo.getBatchNo())) {
                    System.out.println(inventoryVo.getBatchNo());
                    sum=inventoryList.stream().filter(item->item.getBatchName().equals(inventoryVo.getBatchNo())).mapToDouble(item -> item.getQuantity()).sum();
                } else {
                    sum = inventoryList.stream().mapToDouble(item -> item.getQuantity()).sum();
                }
                inventoryVo.setQuantity(sum);
            } else {
                ItemInfo itemInfo = itemInfoService.getOne(new QueryWrapper<ItemInfo>().eq("item_code", inventoryVo.getItemNumber()));
                inventoryVo.setItemName(Optional.ofNullable(itemInfo).map(item -> item.getItemName()).orElse(""));
            }
        }


        if(ObjectUtil.isNotEmpty(itemCode)){
            List<InventoryVo> collect = inventory.stream().filter(item -> item.getItemNumber().equals(itemCode)).filter(item -> !collect1.contains(item.getStockId())).collect(Collectors.toList());
            return ResultGenerator.genSuccessResult(collect);
        }else{

            List<InventoryVo> collect = inventory.stream().filter(item -> !item.getQuantity().equals(item.getQty())).filter(item -> !collect1.contains(item.getStockId())).collect(Collectors.toList());
            return ResultGenerator.genSuccessResult(collect);
        }
    }


}
